#include "api.h"
#include <QApplication>
#include <QEventLoop>
#include <QTimer>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QDateTime>
#include <QRandomGenerator>
#include <QSqlRecord>

// 静态成员初始化
Api* Api::m_instance = nullptr;

Api::Api() : QObject() {
    m_manager = new QNetworkAccessManager(this);
    m_dataCache.setMaxCost(100); // 缓存最多100个项目
}

Api* Api::getInstance() {
    if (m_instance == nullptr) {
        m_instance = new Api();
    }
    return m_instance;
}

void Api::sendRequest(const QString& url,
                     const QByteArray& method,
                     const QJsonObject& params,
                     int timeoutMs,
                     ApiCallback callback) {
    try {
        QNetworkRequest request;
        request.setUrl(QUrl(baseUrl + url));
        request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
        
        // 添加认证token
        if (!m_globalToken.isEmpty()) {
            request.setRawHeader("Authorization", QString("Bearer %1").arg(m_globalToken).toUtf8());
        }
        
        QNetworkReply* reply = nullptr;
        QByteArray data = QJsonDocument(params).toJson();
        
        if (method == "GET") {
            reply = m_manager->get(request);
        } else if (method == "POST") {
            reply = m_manager->post(request, data);
        } else if (method == "PUT") {
            reply = m_manager->put(request, data);
        } else if (method == "DELETE") {
            reply = m_manager->deleteResource(request);
        }
        
        if (reply) {
            // 设置超时
            QTimer::singleShot(timeoutMs, [reply]() {
                if (reply && reply->isRunning()) {
                    reply->abort();
                }
            });
            
            connect(reply, &QNetworkReply::finished, [this, reply, callback, url]() {
                bool success = false;
                QJsonObject response;
                QString errorMsg;
                int statusCode = 0;
                
                try {
                    if (reply) {
                        statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
                        
                        if (reply->error() == QNetworkReply::NoError) {
                            success = true;
                            QByteArray responseData = reply->readAll();
                            QJsonParseError parseError;
                            QJsonDocument doc = QJsonDocument::fromJson(responseData, &parseError);
                            if (parseError.error == QJsonParseError::NoError) {
                                if (doc.isObject()) {
                                    response = doc.object();
                                } else if (doc.isArray()) {
                                    response["data"] = doc.array();
                                } else {
                                    response["data"] = QString(responseData);
                                }
                            } else {
                                success = false;
                                errorMsg = "JSON解析错误: " + parseError.errorString();
                                qDebug() << "JSON Parse Error for URL" << url << ":" << parseError.errorString();
                            }
                        } else {
                            errorMsg = reply->errorString();
                            qDebug() << "Network Error for URL" << url << ":" << errorMsg << "Status:" << statusCode;
                        }
                    } else {
                        errorMsg = "网络请求对象为空";
                        qDebug() << "Reply is null for URL:" << url;
                    }
                } catch (const std::exception& e) {
                    errorMsg = QString("请求处理异常: %1").arg(e.what());
                    qDebug() << "Exception in request processing for URL" << url << ":" << errorMsg;
                } catch (...) {
                    errorMsg = "请求处理发生未知异常";
                    qDebug() << "Unknown exception in request processing for URL:" << url;
                }
                
                if (callback) {
                    try {
                        callback(success, response, errorMsg, statusCode);
                    } catch (const std::exception& e) {
                        qDebug() << "Exception in callback for URL" << url << ":" << e.what();
                    } catch (...) {
                        qDebug() << "Unknown exception in callback for URL:" << url;
                    }
                }
                
                if (reply) {
                    reply->deleteLater();
                }
            });
        } else {
            qDebug() << "Failed to create network request for URL:" << url;
            if (callback) {
                callback(false, QJsonObject(), "无法创建网络请求", 0);
            }
        }
    } catch (const std::exception& e) {
        qDebug() << "Exception in sendRequest for URL" << url << ":" << e.what();
        if (callback) {
            callback(false, QJsonObject(), QString("发送请求异常: %1").arg(e.what()), 0);
        }
    } catch (...) {
        qDebug() << "Unknown exception in sendRequest for URL:" << url;
        if (callback) {
            callback(false, QJsonObject(), "发送请求发生未知异常", 0);
        }
    }
}

void Api::get(const QString& url, const QJsonObject& params, int timeout, ApiCallback callback) {
    sendRequest(url, "GET", params, timeout, callback);
}

void Api::post(const QString& url, const QJsonObject& params, int timeout, ApiCallback callback) {
    sendRequest(url, "POST", params, timeout, callback);
}

void Api::del(const QString& url, const QJsonObject& params, int timeout, ApiCallback callback) {
    sendRequest(url, "DELETE", params, timeout, callback);
}

void Api::put(const QString& url, const QJsonObject& params, int timeout, ApiCallback callback) {
    sendRequest(url, "PUT", params, timeout, callback);
}

void Api::configureHttps(const QString& caCertPath) {
    QSslConfiguration sslConfig = QSslConfiguration::defaultConfiguration();
    if (!caCertPath.isEmpty()) {
        QFile certFile(caCertPath);
        if (certFile.open(QIODevice::ReadOnly)) {
            QSslCertificate cert(&certFile);
            sslConfig.addCaCertificate(cert);
        }
    }
    sslConfig.setProtocol(QSsl::TlsV1_2OrLater);
    QSslConfiguration::setDefaultConfiguration(sslConfig);
}

bool Api::connectDatabase(const QString& dbName) {
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(dbName);
    return db.open();
}

void Api::setupDatabase() {
    if (!connectDatabase()) {
        return;
    }
    
    QSqlQuery query;
    // 创建票种表
    query.exec("CREATE TABLE IF NOT EXISTS tickets ("
               "id INTEGER PRIMARY KEY AUTOINCREMENT,"
               "name TEXT NOT NULL,"
               "price REAL NOT NULL,"
               "description TEXT,"
               "status TEXT DEFAULT 'active',"
               "created_at DATETIME DEFAULT CURRENT_TIMESTAMP,"
               "updated_at DATETIME DEFAULT CURRENT_TIMESTAMP)");
    
    // 创建订单表
    query.exec("CREATE TABLE IF NOT EXISTS orders ("
               "id INTEGER PRIMARY KEY AUTOINCREMENT,"
               "user_id INTEGER,"
               "ticket_id INTEGER,"
               "quantity INTEGER NOT NULL,"
               "total_price REAL NOT NULL,"
               "status TEXT DEFAULT 'pending',"
               "created_at DATETIME DEFAULT CURRENT_TIMESTAMP,"
               "updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,"
               "FOREIGN KEY (ticket_id) REFERENCES tickets(id))");
    
    // 创建用户表
    query.exec("CREATE TABLE IF NOT EXISTS users ("
               "id INTEGER PRIMARY KEY AUTOINCREMENT,"
               "username TEXT UNIQUE NOT NULL,"
               "email TEXT UNIQUE NOT NULL,"
               "phone TEXT,"
               "status TEXT DEFAULT 'active',"
               "created_at DATETIME DEFAULT CURRENT_TIMESTAMP,"
               "updated_at DATETIME DEFAULT CURRENT_TIMESTAMP)");
}

void Api::insertSampleData() {
    QSqlQuery query;
    query.exec("INSERT INTO tickets (name, price, description) VALUES "
               "('成人票', 100.0, '标准成人票'),"
               "('儿童票', 50.0, '儿童专用票'),"
               "('学生票', 60.0, '学生优惠票')");
}

void Api::insertSampleOrders() {
    QSqlQuery query;
    query.exec("INSERT INTO orders (user_id, ticket_id, quantity, total_price, status) VALUES "
               "(1, 1, 2, 200.0, 'completed'),"
               "(2, 2, 1, 50.0, 'completed'),"
               "(3, 3, 3, 180.0, 'pending')");
}

void Api::getTickets(const QJsonObject& params, ApiCallback callback) {
    get("/api/tickets", params, 5000, callback);
}

void Api::addTicket(const QJsonObject& params, ApiCallback callback) {
    post("/api/tickets", params, 5000, callback);
}

void Api::updateTicket(const QJsonObject& params, ApiCallback callback) {
    QString ticketId = params["id"].toString();
    put(QString("/api/tickets/%1").arg(ticketId), params, 5000, callback);
}

void Api::deleteTicket(const QString& ticketId, ApiCallback callback) {
    del(QString("/api/tickets/%1").arg(ticketId), {}, 5000, callback);
}

void Api::searchTicketsWithParams(const QJsonObject& searchParams, ApiCallback callback) {
    get("/api/tickets/search", searchParams, 5000, callback);
}

void Api::deleteTicketWithParams(const QString& ticketId, const QJsonObject& params, ApiCallback callback) {
    del(QString("/api/tickets/%1").arg(ticketId), params, 5000, callback);
}

void Api::getOrders(const QJsonObject& params, ApiCallback callback) {
    get("/api/orders", params, 5000, callback);
}

void Api::updateOrder(const QJsonObject& params, ApiCallback callback) {
    QString orderId = params["id"].toString();
    put(QString("/api/orders/%1").arg(orderId), params, 5000, callback);
}

void Api::deleteOrder(const QString& orderId, ApiCallback callback) {
    del(QString("/api/orders/%1").arg(orderId), {}, 5000, callback);
}

void Api::getOrderStatistics(ApiCallback callback) {
    get("/api/orders/statistics", {}, 5000, callback);
}

void Api::getUsers(const QJsonObject& params, ApiCallback callback) {
    get("/api/users", params, 5000, callback);
}

QJsonObject Api::getUsers(int page, int pageSize) {
    QJsonObject result;
    QJsonArray users;
    
    // 模拟数据
    for (int i = 1; i <= pageSize; ++i) {
        QJsonObject user;
        user["id"] = (page - 1) * pageSize + i;
        user["username"] = QString("用户%1").arg((page - 1) * pageSize + i);
        user["email"] = QString("user%1@example.com").arg((page - 1) * pageSize + i);
        user["status"] = "active";
        users.append(user);
    }
    
    result["users"] = users;
    result["total"] = 100; // 模拟总数
    result["page"] = page;
    result["pageSize"] = pageSize;
    
    return result;
}

void Api::searchUsers(const QString& searchText, int page, int pageSize, ApiCallback callback) {
    QJsonObject params;
    params["search"] = searchText;
    params["page"] = page;
    params["pageSize"] = pageSize;
    get("/api/users/search", params, 5000, callback);
}

QJsonObject Api::getUserStatistics() {
    QJsonObject stats;
    stats["totalUsers"] = 150;
    stats["activeUsers"] = 120;
    stats["inactiveUsers"] = 30;
    stats["newUsersThisMonth"] = 15;
    return stats;
}

QJsonObject Api::getUserDetails(int userId) {
    QJsonObject user;
    user["id"] = userId;
    user["username"] = QString("用户%1").arg(userId);
    user["email"] = QString("user%1@example.com").arg(userId);
    user["phone"] = QString("1380000%1").arg(userId % 10000, 4, 10, QChar('0'));
    user["status"] = "active";
    user["createdAt"] = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    return user;
}

QJsonObject Api::freezeUser(int userId) {
    QJsonObject result;
    result["success"] = true;
    result["message"] = QString("用户 %1 已被冻结").arg(userId);
    return result;
}

QJsonObject Api::unfreezeUser(int userId) {
    QJsonObject result;
    result["success"] = true;
    result["message"] = QString("用户 %1 已被解冻").arg(userId);
    return result;
}

void Api::deleteUser(int userId, ApiCallback callback) {
    del(QString("/api/users/%1").arg(userId), {}, 5000, callback);
}

void Api::getDashboardStatistics(ApiCallback callback) {
    get("/api/dashboard/statistics", {}, 5000, callback);
}

void Api::getRevenueChartData(const QString& timeRange, ApiCallback callback) {
    QJsonObject params;
    params["timeRange"] = timeRange;
    get("/api/revenue/chart", params, 5000, callback);
}

void Api::getCategoryChartData(const QString& timeRange, ApiCallback callback) {
    QJsonObject params;
    params["timeRange"] = timeRange;
    get("/api/revenue/category", params, 5000, callback);
}

void Api::getDetailedStatistics(ApiCallback callback) {
    get("/api/statistics/detailed", {}, 5000, callback);
}

QString Api::getPreviousTimeRange(const QString& timeRange) {
    if (timeRange == "today") {
        return "yesterday";
    } else if (timeRange == "thisWeek") {
        return "lastWeek";
    } else if (timeRange == "thisMonth") {
        return "lastMonth";
    } else if (timeRange == "thisYear") {
        return "lastYear";
    }
    return timeRange;
}

void Api::getSourceAnalysisData(const QString& dimension, const QJsonObject& params, ApiCallback callback) {
    // 参数验证
    if (dimension.isEmpty()) {
        if (callback) {
            callback(false, createErrorResponse("维度参数不能为空"), "维度参数不能为空", 400);
        }
        return;
    }
    
    // 构建请求参数
    QJsonObject requestParams = params;
    requestParams["dimension"] = dimension;
    
    // 首先尝试从API获取数据
    get("/api/v1/income/source-analysis", requestParams, 3000, [this, dimension, callback](bool success, const QJsonObject& response, const QString& errorMsg, int statusCode) {
        if (success) {
            // API成功，返回真实数据
            if (callback) callback(true, response, "", statusCode);
        } else {
            // API失败，返回模拟数据
            qDebug() << "API failed, using fallback data for source analysis. Error:" << errorMsg;
            QJsonObject fallbackResponse = generateSourceAnalysisFallback(dimension);
            if (callback) callback(true, fallbackResponse, "", 200);
        }
    });
}

void Api::getIncomeStatistics(ApiCallback callback) {
    // 首先尝试从API获取数据
    get("/api/v1/income/statistics", {}, 3000, [this, callback](bool success, const QJsonObject& response, const QString& errorMsg, int statusCode) {
        if (success) {
            // API成功，返回真实数据
            if (callback) callback(true, response, "", statusCode);
        } else {
            // API失败，返回模拟数据
            qDebug() << "API failed, using fallback data for income statistics. Error:" << errorMsg;
            QJsonObject fallbackResponse = generateIncomeStatisticsFallback();
            if (callback) callback(true, fallbackResponse, "", 200);
        }
    });
}

QJsonObject Api::generateIncomeStatisticsFallback() {
    QJsonObject response;
    response["success"] = true;
    response["message"] = "使用模拟数据（API服务器不可用）";
    
    // 生成模拟的收入统计数据 - 返回原始数据用于手动计算变化率
    QDateTime now = QDateTime::currentDateTime();
    
    // 当日收入数据
    response["todayIncome"] = QString::number(125680.50 + (QRandomGenerator::global()->bounded(10000) - 5000), 'f', 2);
    response["yesterdayIncome"] = QString::number(115890.25 + (QRandomGenerator::global()->bounded(8000) - 4000), 'f', 2);
    
    // 当月收入数据
    response["thisMonthIncome"] = QString::number(3580240.75 + (QRandomGenerator::global()->bounded(100000) - 50000), 'f', 2);
    response["lastMonthIncome"] = QString::number(3189560.50 + (QRandomGenerator::global()->bounded(80000) - 40000), 'f', 2);
    
    // 当年收入数据
    response["thisYearIncome"] = QString::number(42580320.00 + (QRandomGenerator::global()->bounded(1000000) - 500000), 'f', 2);
    response["lastYearIncome"] = QString::number(36785420.75 + (QRandomGenerator::global()->bounded(800000) - 400000), 'f', 2);
    
    // 小时收入数据（用于实时增长率计算）
    response["thisHourIncome"] = QString::number(5680.25 + (QRandomGenerator::global()->bounded(2000) - 1000), 'f', 2);
    response["lastHourIncome"] = QString::number(4890.50 + (QRandomGenerator::global()->bounded(1500) - 750), 'f', 2);
    
    // 新增：近24小时收入统计数据
    QJsonArray hourlyData;
    double baseIncome = 5000.0;
    for (int i = 23; i >= 0; i--) {
        QDateTime time = now.addSecs(-i * 3600);
        QJsonObject hourData;
        hourData["time"] = time.toString("yyyy-MM-dd hh:mm:ss");
        hourData["hour"] = time.toString("HH:mm");
        
        // 模拟真实的收入波动模式
        double hourFactor = 1.0;
        int hour = time.time().hour();
        
        if (hour >= 8 && hour <= 10) hourFactor = 1.5; // 上午高峰
        else if (hour >= 14 && hour <= 16) hourFactor = 1.3; // 下午高峰
        else if (hour >= 19 && hour <= 21) hourFactor = 1.4; // 晚间高峰
        else if (hour >= 0 && hour <= 6) hourFactor = 0.3; // 深夜低谷
        else if (hour >= 22 || hour <= 7) hourFactor = 0.5; // 夜间低谷
        
        double randomFactor = 0.8 + (QRandomGenerator::global()->bounded(40) / 100.0);
        double income = baseIncome * hourFactor * randomFactor;
        
        hourData["income"] = QString::number(income, 'f', 2);
        hourlyData.append(hourData);
    }
    response["last24HoursData"] = hourlyData;
    
    // 更新时间
    response["updateTime"] = now.toString("yyyy-MM-dd hh:mm:ss");
    
    return response;
}

// 游戏内容管理相关API方法实现
void Api::getGameContents(const QJsonObject& params, ApiCallback callback) {
    get("/api/v1/game-contents", params, 5000, callback);
}

void Api::addGameContent(const QJsonObject& params, ApiCallback callback) {
    post("/api/v1/game-contents", params, 5000, callback);
}

void Api::updateGameContent(const QJsonObject& params, ApiCallback callback) {
    put(QString("/api/v1/game-contents"), params, 5000, callback);
}

void Api::deleteGameContent(const QString& contentId, ApiCallback callback) {
    QJsonObject params;
    params["id"] = contentId;
    del(QString("/api/v1/game-contents"), params, 5000, callback);
}

// 公告管理相关API方法实现
void Api::getAnnouncements(const QJsonObject& params, ApiCallback callback) {
    get("/api/v1/announcements", params, 5000, callback);
}

void Api::addAnnouncement(const QJsonObject& params, ApiCallback callback) {
    post("/api/v1/announcements", params, 5000, callback);
}

void Api::updateAnnouncement(const QJsonObject& params, ApiCallback callback) {
    put(QString("/api/v1/announcements"), params, 5000, callback);
}

void Api::deleteAnnouncement(const QString& announcementId, ApiCallback callback) {
    QJsonObject params;
    params["id"] = announcementId;
    del(QString("/api/v1/announcements"), params, 5000, callback);
}

void Api::getAnnouncementDetail(const QString& announcementId, ApiCallback callback) {
    QJsonObject params;
    params["id"] = announcementId;
    get(QString("/api/v1/announcements"), params, 5000, callback);
}

void Api::getIncomeTrendAnalysisData(const QString& startDate, const QString& endDate, const QString& period, ApiCallback callback) {
    // 参数验证
    if (startDate.isEmpty() || endDate.isEmpty() || period.isEmpty()) {
        if (callback) {
            callback(false, createErrorResponse("参数不能为空"), "参数不能为空", 400);
        }
        return;
    }
    
    // 构建请求参数
    QJsonObject params;
    params["startDate"] = startDate;
    params["endDate"] = endDate;
    params["period"] = period;
    
    // 首先尝试从API获取数据
    get("/api/v1/income/trend-analysis", params, 3000, [this, startDate, endDate, period, callback](bool success, const QJsonObject& response, const QString& errorMsg, int statusCode) {
        if (success) {
            // API成功，返回真实数据
            if (callback) callback(true, response, "", statusCode);
        } else {
            // API失败，返回模拟数据
            qDebug() << "API failed, using fallback data for trend analysis. Error:" << errorMsg;
            QJsonObject fallbackResponse = generateTrendAnalysisFallback(startDate, endDate, period);
            if (callback) callback(true, fallbackResponse, "", 200);
        }
    });
}

QJsonObject Api::generateTrendAnalysisFallback(const QString& startDate, const QString& endDate, const QString& period) {
    // 模拟数据结构
    QJsonObject response;
    response["success"] = true;
    response["message"] = "使用模拟数据（API服务器不可用）";
    
    // 生成基础收入数据
    double baseIncome = QRandomGenerator::global()->bounded(100000, 500000);
    
    // 根据周期生成相应的数据
    if (period.contains("周")) {
        // 按周分析 - 生成周度比较数据
        response["currentWeekIncome"] = QString::number(baseIncome * 7, 'f', 2);
        response["previousWeekIncome"] = QString::number(baseIncome * 7 * 0.88, 'f', 2); // 上周收入略低
        
        // 生成当周每天的收入数据
        QJsonArray weekDailyData;
        for (int i = 0; i < 7; i++) { // 一周7天
            QJsonObject dayData;
            dayData["dayNumber"] = QString::number(i + 1); // 1-7
            // 周末收入略高
            double dayMultiplier = 0.9 + QRandomGenerator::global()->bounded(0.3);
            if (i >= 5) dayMultiplier = 1.2; // 周六、周日收入较高
            if (i == 2) dayMultiplier = 1.1; // 周三略高
            dayData["income"] = QString::number(baseIncome * dayMultiplier, 'f', 2);
            weekDailyData.append(dayData);
        }
        response["weekDailyData"] = weekDailyData;
    } else if (period.contains("月")) {
        // 按月分析 - 生成月度比较数据
        response["currentMonthIncome"] = QString::number(baseIncome * 30, 'f', 2);
        response["previousMonthIncome"] = QString::number(baseIncome * 30 * 0.88, 'f', 2); // 上月收入略低
        
        // 生成当月每周的收入数据
        QJsonArray monthWeeklyData;
        for (int i = 0; i < 4; i++) { // 一个月约4周
            QJsonObject weekData;
            weekData["week"] = QString::number(i + 1); // 第1周到第4周
            // 月初和月末的周收入略高
            double weekMultiplier = 0.9 + QRandomGenerator::global()->bounded(0.3);
            if (i == 0 || i == 3) weekMultiplier = 1.1; // 第一周和第四周收入略高
            if (i == 2) weekMultiplier = 1.2; // 第三周收入最高
            weekData["income"] = QString::number(baseIncome * 7 * weekMultiplier, 'f', 2); // 每周收入
            monthWeeklyData.append(weekData);
        }
        response["monthWeeklyData"] = monthWeeklyData;
    } else if (period.contains("年")) {
        // 按年分析 - 生成年度比较数据
        response["currentYearIncome"] = QString::number(baseIncome * 365, 'f', 2);
        response["previousYearIncome"] = QString::number(baseIncome * 365 * 0.8, 'f', 2); // 去年收入较低
        
        // 生成当年每月的收入数据
        QJsonArray yearMonthlyData;
        for (int i = 0; i < 12; i++) {
            QJsonObject monthData;
            monthData["month"] = QString::number(i + 1); // 1月到12月
            // 节假日月份收入略高
            double monthMultiplier = 0.9 + QRandomGenerator::global()->bounded(0.3);
            if (i == 0 || i == 1 || i == 9 || i == 11) monthMultiplier = 1.2; // 春节、国庆、元旦等假期月份
            monthData["income"] = QString::number(baseIncome * 30 * monthMultiplier, 'f', 2);
            yearMonthlyData.append(monthData);
        }
        response["yearMonthlyData"] = yearMonthlyData;
    }
    
    // 生成趋势数据数组
    QJsonArray trendData;
    int dataPoints = 0;
    QString timeUnit = "";
    
    if (period.contains("周")) {
        dataPoints = 7; // 按天
        timeUnit = "天";
    } else if (period.contains("月")) {
        dataPoints = 4; // 按天
        timeUnit = "周";
    } else if (period.contains("年")) {
        dataPoints = 12; // 按月
        timeUnit = "月";
    }
    
    if (dataPoints > 0) {
        double startValue = baseIncome / dataPoints;
        double growthFactor = 1.0 + (QRandomGenerator::global()->bounded(0.1) - 0.05); // 随机增长因子
        
        for (int i = 0; i < dataPoints; i++) {
            QJsonObject point;
            point["time"] = i + 1;
            point["timeUnit"] = timeUnit;
            point["income"] = QString::number(startValue * qPow(growthFactor, i) * (0.9 + QRandomGenerator::global()->bounded(0.2)), 'f', 2);
            trendData.append(point);
        }
    }
    
    response["trendData"] = trendData;
    response["period"] = period;
    response["startDate"] = startDate;
    response["endDate"] = endDate;
    
    return response;
}

QJsonObject Api::generateSourceAnalysisFallback(const QString& dimension) {
    // 模拟数据结构
    QJsonObject response;
    response["code"] = 200;
    response["msg"] = "success";
    
    QJsonObject data;
    QJsonArray sourceData;
    
    // 根据不同维度生成模拟数据
    if (dimension == "车次类型") {
        QJsonObject item1; item1["name"] = "高铁"; item1["value"] = 78200.65; item1["count"] = 580; item1["percentage"] = 45.2; sourceData.append(item1);
        QJsonObject item2; item2["name"] = "动车"; item2["value"] = 48500.30; item2["count"] = 420; item2["percentage"] = 28.0; sourceData.append(item2);
        QJsonObject item3; item3["name"] = "普通列车"; item3["value"] = 29800.45; item3["count"] = 240; item3["percentage"] = 17.2; sourceData.append(item3);
        QJsonObject item4; item4["name"] = "其他车型"; item4["value"] = 16500.20; item4["count"] = 105; item4["percentage"] = 9.5; sourceData.append(item4);
    } else if (dimension == "座位等级") {
        QJsonObject item1; item1["name"] = "一等座"; item1["value"] = 82300.75; item1["count"] = 410; item1["percentage"] = 46.8; sourceData.append(item1);
        QJsonObject item2; item2["value"] = 58900.50; item2["name"] = "二等座"; item2["count"] = 720; item2["percentage"] = 33.5; sourceData.append(item2);
        QJsonObject item3; item3["value"] = 26700.35; item3["name"] = "商务座"; item3["count"] = 145; item3["percentage"] = 15.2; sourceData.append(item3);
        QJsonObject item4; item4["value"] = 7800.20; item4["name"] = "无座"; item4["count"] = 185; item4["percentage"] = 4.4; sourceData.append(item4);
    } else if (dimension == "出发/到达站") {
        QJsonObject item1; item1["value"] = 42500.75; item1["name"] = "北京"; item1["count"] = 310; item1["percentage"] = 25.8; sourceData.append(item1);
        QJsonObject item2; item2["value"] = 36200.60; item2["name"] = "上海"; item2["count"] = 280; item2["percentage"] = 21.9; sourceData.append(item2);
        QJsonObject item3; item3["value"] = 31500.45; item3["name"] = "广州"; item3["count"] = 240; item3["percentage"] = 19.1; sourceData.append(item3);
        QJsonObject item4; item4["value"] = 27800.30; item4["name"] = "深圳"; item4["count"] = 215; item4["percentage"] = 16.8; sourceData.append(item4);
        QJsonObject item5; item5["value"] = 10700.25; item5["name"] = "其他"; item5["count"] = 255; item5["percentage"] = 6.5; sourceData.append(item5);
    } else if (dimension == "时间段客流量") {
        QJsonObject item1; item1["value"] = 45800.60; item1["name"] = "早高峰(7-9点)"; item1["count"] = 420; item1["percentage"] = 31.5; sourceData.append(item1);
        QJsonObject item2; item2["value"] = 38200.45; item2["name"] = "晚高峰(17-19点)"; item2["count"] = 360; item2["percentage"] = 26.1; sourceData.append(item2);
        QJsonObject item3; item3["value"] = 27500.30; item3["name"] = "中午时段(12-14点)"; item3["count"] = 285; item3["percentage"] = 18.8; sourceData.append(item3);
        QJsonObject item4; item4["value"] = 34500.25; item4["name"] = "其他时段"; item4["count"] = 485; item4["percentage"] = 23.7; sourceData.append(item4);
    } else {
        // 默认维度数据
        QJsonObject item1; item1["value"] = 52000.00; item1["name"] = "类别1"; item1["count"] = 390; item1["percentage"] = 30.2; sourceData.append(item1);
        QJsonObject item2; item2["value"] = 41000.00; item2["name"] = "类别2"; item2["count"] = 330; item2["percentage"] = 23.8; sourceData.append(item2);
        QJsonObject item3; item3["value"] = 35000.00; item3["name"] = "类别3"; item3["count"] = 280; item3["percentage"] = 20.3; sourceData.append(item3);
        QJsonObject item4; item4["value"] = 28500.00; item4["name"] = "类别4"; item4["count"] = 225; item4["percentage"] = 16.5; sourceData.append(item4);
    }
    
    data["sourceData"] = sourceData;
    response["data"] = data;
    
    return response;
}


QString Api::generateCacheKey(const QString& url, const QJsonObject& params) {
    QJsonDocument doc(params);
    return url + ":" + doc.toJson(QJsonDocument::Compact).toBase64();
}

bool Api::isRequestPending(const QString& cacheKey) {
    QMutexLocker locker(&m_pendingMutex);
    return m_pendingRequests.contains(cacheKey);
}

void Api::addPendingRequest(const QString& cacheKey, ApiCallback callback) {
    QMutexLocker locker(&m_pendingMutex);
    m_pendingRequests.insert(cacheKey);
    m_requestCallbacks[cacheKey].append(callback);
}

void Api::removePendingRequest(const QString& cacheKey) {
    QMutexLocker locker(&m_pendingMutex);
    m_pendingRequests.remove(cacheKey);
    m_requestCallbacks.remove(cacheKey);
}

void Api::executePendingCallbacks(const QString& cacheKey, bool success, const QJsonObject& response, const QString& errorMsg, int statusCode) {
    QMutexLocker locker(&m_pendingMutex);
    if (m_requestCallbacks.contains(cacheKey)) {
        for (auto& callback : m_requestCallbacks[cacheKey]) {
            if (callback) {
                callback(success, response, errorMsg, statusCode);
            }
        }
        m_requestCallbacks.remove(cacheKey);
    }
}

void Api::logPerformanceMetrics(const QString& operation, qint64 elapsedMs) {
    m_requestTimes[operation] = elapsedMs;
    qDebug() << "Operation" << operation << "took" << elapsedMs << "ms";
}

bool Api::shouldRetryRequest(const QString& cacheKey, int statusCode) {
    // 对于服务器错误(5xx)和网络错误，可以重试
    return (statusCode >= 500 || statusCode == 0) && m_retryCount[cacheKey] < 3;
}

QJsonObject Api::createErrorResponse(const QString& message, const QString& operation) {
    QJsonObject error;
    error["success"] = false;
    error["error"] = message;
    error["operation"] = operation;
    error["timestamp"] = QDateTime::currentDateTime().toString(Qt::ISODate);
    return error;
}

void Api::handleRequestError(const QString& cacheKey, const QString& errorMsg, int statusCode, ApiCallback callback) {
    if (shouldRetryRequest(cacheKey, statusCode)) {
        m_retryCount[cacheKey]++;
        // 可以在这里实现重试逻辑
    } else {
        QJsonObject errorResponse = createErrorResponse(errorMsg, cacheKey);
        if (callback) {
            callback(false, errorResponse, errorMsg, statusCode);
        }
        removePendingRequest(cacheKey);
    }
}

void Api::getCached(const QString& url, const QJsonObject& params, int timeoutMs, ApiCallback callback, bool useCache, int cacheTimeoutMs) {
    QString cacheKey = generateCacheKey(url, params);
    
    if (useCache) {
        QMutexLocker locker(&m_cacheMutex);
        if (m_dataCache.contains(cacheKey)) {
            QJsonObject* cachedData = m_dataCache.object(cacheKey);
            if (cachedData && callback) {
                callback(true, *cachedData, "", 200);
                return;
            }
        }
    }
    
    if (isRequestPending(cacheKey)) {
        addPendingRequest(cacheKey, callback);
        return;
    }
    
    addPendingRequest(cacheKey, callback);
    
    get(url, params, timeoutMs, [this, cacheKey, callback, useCache](bool success, const QJsonObject& response, const QString& errorMsg, int statusCode) {
        if (success && useCache) {
            QMutexLocker locker(&m_cacheMutex);
            m_dataCache.insert(cacheKey, new QJsonObject(response));
        }
        
        executePendingCallbacks(cacheKey, success, response, errorMsg, statusCode);
        removePendingRequest(cacheKey);
    });
}

void Api::clearCache(const QString& pattern) {
    QMutexLocker locker(&m_cacheMutex);
    if (pattern.isEmpty()) {
        m_dataCache.clear();
    } else {
        // 可以实现模式匹配清理
        m_dataCache.clear();
    }
}

QJsonObject Api::getPerformanceStats() {
    QJsonObject stats;
    
    // Convert QHash<QString, qint64> to QJsonObject
    QJsonObject requestTimesObj;
    for (auto it = m_requestTimes.begin(); it != m_requestTimes.end(); ++it) {
        requestTimesObj[it.key()] = static_cast<double>(it.value());
    }
    stats["requestTimes"] = requestTimesObj;
    stats["cacheSize"] = m_dataCache.size();
    stats["pendingRequests"] = m_pendingRequests.size();
    return stats;
}
